package com.etlmaster.executor;

import java.util.List;

import com.etlmaster.executor.utils.DpExecutorDbLogUtils;
import com.etlmaster.executor.utils.StepState;
import com.etlmaster.jdbc.JdbcTemplate;

public abstract class Step {
	
	private Boolean ignoreLog=false; 

	private StepMeta meta;
	
	protected abstract int handle();
	

	public abstract boolean stop();
	
	public boolean suspend(){
	/*	try {
			wait();
			status.set(SUSPENDED);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}*/
		return true;
	}
	public void run(JobMeta jobMeta){
		meta.getStepState().setStatus(StepState.RUNNING);
		boolean runningState = false;
		int doNumber = 0;
		boolean doing = false;
		while(!runningState && (doing = (meta.getRedo()-doNumber) >= 0)){
			try{
				int StepStateCode=0;
				if(meta.isSkipFlag()){
					 StepStateCode=0;
					 meta.log("INFO","步骤忽略");
				}else{
					//增加日志记录
					ignoreLog= Boolean.parseBoolean( (String) JobPool.getVariable(meta.getSession_id()).get("ignore"));
					
					if(!ignoreLog){
						DpExecutorDbLogUtils.logStepStart(meta.getSession_id(),meta.getId(),meta.getStep_code(), jobMeta.getName(), JobPool.getVariable(meta.getSession_id()).get("taskid").toString(),  meta.getName());
					}
					//1 失败 0 成功
					StepStateCode = handle();
					
					if(!ignoreLog){
						String sql_text=meta.getStepState().getReturnValue().get("logInfo")!=null?meta.getStepState().getReturnValue().get("logInfo").toString():"";
						DpExecutorDbLogUtils.logStepEnd(meta.getSession_id(),meta.getId(),meta.getStep_code(), jobMeta.getName(), JobPool.getVariable(jobMeta.getSeesionId()).get("taskid").toString(),meta.getName(),sql_text, StepStateCode);
					}
				}
				meta.getStepState().setStatus(StepStateCode);

				doing = true;
			}catch(Exception e){
				meta.getStepState().setStatus(StepState.ABORTED);
				meta.log("ERROR","执行错误,{},{}",e.getMessage(),jobMeta.getSeesionId());
			}
			doNumber++;
		}
	}

	public boolean resume(){
		/*notify();
		status.set(RUNNING);*/
		return true;
	}
	
	public Step(StepMeta meta){
		this.meta=meta;
	}
	
	public List<StepMeta> getNextSteps(){
		return null;
	}
	
	public StepMeta getMeta() {
		return meta;
	}

	public void setMeta(StepMeta meta) {
		this.meta = meta;
	}
	
	public String getStepId(){
		return meta.getId();
	}
	
	protected JdbcTemplate getJdbcTemplate(){
		return new JdbcTemplate();
	}

}
